using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DragonAwakening.Game;
using Microsoft.Xna.Framework;
using DragonAwakening.Core.Game;

namespace DragonAwakening.Core.World
{
    /// <summary>
    /// Starting point processor
    /// </summary>
    public class WorldStartPointProcessor : WorldDataProcessor
    {
        /// <summary>
        /// Game context.
        /// </summary>
        private IGameContext context;

        /// <summary>
        /// Creates the processor.
        /// </summary>
        public WorldStartPointProcessor(IWorldDataProcessor next, IWorld world, IGameContext context)
            : base(next, world)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            this.context = context;
        }

        /// <summary>
        /// Process the data.
        /// </summary>
        public override void Process(string data, int index)
        {
            string widthChunk, heightChunk;
            int nextIndex = this.TryReadDataChunk(data, index, out widthChunk);
            if (nextIndex == -1)
            {
                // [LOG] Error: Start point X isn't defined.
                return;
            }

            nextIndex = this.TryReadDataChunk(data, nextIndex, out heightChunk);
            if (nextIndex == -1)
            {
                // [LOG] Error: Start point Y isn't defined.
            }

            string direction;
            nextIndex = this.TryReadDataChunk(data, nextIndex, out direction);
            if (nextIndex == -1)
            {
                // [LOG] Error: Start direction isn't defined.
            }
            
            int x = 0, y = 0;

            bool isDataValid = !string.IsNullOrWhiteSpace(widthChunk) && !string.IsNullOrWhiteSpace(heightChunk);
            bool areChunksParsed = isDataValid && int.TryParse(widthChunk, out x) && int.TryParse(heightChunk, out y);
            bool areDimentionsValid = areChunksParsed && y > 0 && x > 0;

            if (areDimentionsValid)
            {
                this.context.SetPlayerCurrentPosition(new Point(x, y));

                try
                {
                    this.context.SetPlayerCurrentDirection((Sides)Enum.Parse(typeof(Sides), direction, true));
                }
                catch (Exception e)
                {
                    // [LOG] Error: Starting direction is invalid.
                }
                
                this.InvokeNextProcessor(data, nextIndex);
            }
            else
            {
                // [LOG] Error: Starting position and direction are invalid or zero.
            }
        }
    }
}
